package com.qc31.monitorlib.ui.video.view

import android.content.Context
import android.media.AudioManager
import android.text.TextUtils
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.RelativeLayout
import android.widget.TextView
import com.qc31.monitorlib.R
import com.qc31.monitorlib.ui.video.RealVideoManager
import com.qc31.monitorlib.ui.video.observer.ChooseObserver
import com.qc31.monitorlib.ui.video.observer.ChooseVideoUtil
import com.qc31.monitorlib.ui.video.observer.NeedMutesObserver
import com.qc31.monitorlib.ui.video.observer.NeedMutesUtil
import com.shuyu.gsyvideoplayer.utils.GSYVideoType
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer
import com.shuyu.gsyvideoplayer.video.base.GSYBaseVideoPlayer
import com.shuyu.gsyvideoplayer.video.base.GSYVideoPlayer
import com.shuyu.gsyvideoplayer.video.base.GSYVideoView
import com.shuyu.gsyvideoplayer.video.base.GSYVideoViewBridge

/** @Author Jasper @Time 2020/9/11 @Desc 自定义实时视频播放 */
class RealVideo : StandardGSYVideoPlayer, NeedMutesObserver, ChooseObserver {


    //是否需要静音
    private var isNeedMute = true

    //记住切换数据源类型
    private var mScaleType = 0

    //是否主码流
    private var isMainStream = false

    private var isChoose = false

    //是否是选中了当前的
    private var isThis = false


    private lateinit var tvSwitchScale: TextView
    private lateinit var tvSwitchStream: TextView
    private lateinit var ivSwitchVoice: ImageView
    private lateinit var rlVideo: RelativeLayout
    private lateinit var loadingProgress: ProgressBar

    constructor(context: Context?, fullFlag: Boolean?) : super(context, fullFlag)
    constructor(context: Context?) : super(context)

    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)

    override fun getLayoutId(): Int {
        return R.layout.real_video
    }

    override fun init(context: Context?) {
        super.init(context)

        tvSwitchScale = findViewById(R.id.tvSwitchScale)
        tvSwitchStream = findViewById(R.id.tvSwitchStream)
        loadingProgress = findViewById(R.id.loadingProgress)
        ivSwitchVoice = findViewById(R.id.ivSwitchVoice)
        rlVideo = findViewById(R.id.rlVideo)
        isRotateViewAuto = true //是否开启制动旋转
        setIsTouchWigetFull(false)
        isLockLand = true

        onAudioFocusChangeListener = AudioManager.OnAudioFocusChangeListener { focusChange: Int ->
            when (focusChange) {
                AudioManager.AUDIOFOCUS_GAIN -> {
                }
                AudioManager.AUDIOFOCUS_LOSS -> {
                }
                AudioManager.AUDIOFOCUS_LOSS_TRANSIENT -> {
                }
                AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK -> {
                }
            }
        }
        ivSwitchVoice.isSelected = true
        setListener()
        tvSwitchScale.setText(R.string.desc_video_default_ratio)
        GSYVideoType.setShowType(GSYVideoType.SCREEN_TYPE_DEFAULT)
    }

    override fun onClick(v: View) {
        super.onClick(v)
        if (v.id == R.id.surface_container) {
            if (!isThis) {
                isChoose = !isChoose
                ChooseVideoUtil.instance.setChoose(getKey(), isChoose)
            }
        }
    }

    /** 修改此处方可配合isLockLand设置自动旋转全屏isVerticalVideo需要取反 */
    override fun isLockLandByAutoFullSize(): Boolean {
        var isLockLand = mLockLand
        if (isAutoFullWithSize) {
            isLockLand = !isVerticalVideo
        }
        return isLockLand
    }

    private fun setListener() {
        //切换码流
        tvSwitchStream.setOnClickListener {
            if (!mHadPlay) {
                return@setOnClickListener
            }
            isMainStream = !isMainStream
            streamChangeListener?.onChange(isMainStream)
            resolveStreamUI()
        }
        //切换比例
        tvSwitchScale.setOnClickListener {

            when (mScaleType) {
                0 -> {
                    mScaleType = 1
                }
                1 -> {
                    mScaleType = 2
                }
                2 -> {
                    mScaleType = 3
                }
                3 -> {
                    mScaleType = 0
                }
            }
            resolveTypeUI()
        }
        //切换声音
        ivSwitchVoice.setOnClickListener {
            ChooseVideoUtil.instance.setTalk(true)
            isNeedMute = !isNeedMute
            ivSwitchVoice.isSelected = isNeedMute
            NeedMutesUtil.instance.setAudioState(getKey(), isNeedMute)
        }
    }

    override fun updateStartImage() {
        if (mStartButton == null) return
        if (mStartButton is ImageView) {
            val imageView = mStartButton as ImageView
            when (mCurrentState) {
                GSYVideoView.CURRENT_STATE_PLAYING -> {
                    imageView.setImageResource(R.mipmap.video_pause_pressed)
                }
                GSYVideoView.CURRENT_STATE_ERROR -> {
                    imageView.setImageResource(R.mipmap.video_play_normal)
                }
                else -> {
                    imageView.setImageResource(R.mipmap.video_play_normal)
                }
            }
        }
    }

    /** 显示比例 注意，GSYVideoType.setShowType是全局静态生效，除非重启APP。 */
    private fun resolveTypeUI() {
        if (!mHadPlay) {
            return
        }
        when (mScaleType) {
            1 -> {
                tvSwitchScale.text = "16:9"
                GSYVideoType.setShowType(GSYVideoType.SCREEN_TYPE_16_9)
            }
            2 -> {
                tvSwitchScale.text = "4:3"
                GSYVideoType.setShowType(GSYVideoType.SCREEN_TYPE_4_3)
            }
            3 -> {
                tvSwitchScale.setText(R.string.desc_video_full_screen)
                GSYVideoType.setShowType(GSYVideoType.SCREEN_TYPE_FULL)
            }
            0 -> {
                tvSwitchScale.setText(R.string.desc_video_default_ratio)
                GSYVideoType.setShowType(GSYVideoType.SCREEN_TYPE_DEFAULT)
            }
        }
        changeTextureViewShowType()
        if (mTextureView != null) mTextureView.requestLayout()
    }

    private fun resolveStreamUI() {
        if (isMainStream) {
            tvSwitchStream.setText(R.string.desc_video_main_stream)
        } else {
            tvSwitchStream.setText(R.string.desc_video_sub_stream)
        }
    }

    private fun resolveVoice() {
        ivSwitchVoice.isSelected = isNeedMute
    }


    /** 是否展示加载 */
    fun showProgress(isShow: Boolean) {
        if (isShow) {
            loadingProgress.visibility = View.VISIBLE
            mStartButton.visibility = View.GONE
        } else {
            loadingProgress.visibility = View.GONE
        }
    }

    fun getKey(): String {
        if (TextUtils.isEmpty(mPlayTag)) {
            mPlayTag = System.currentTimeMillis().toString() + mPlayPosition
        }
        return mPlayTag
    }


    override fun startWindowFullscreen(
        context: Context?,
        actionBar: Boolean,
        statusBar: Boolean
    ): GSYBaseVideoPlayer {
        val video: RealVideo =
            super.startWindowFullscreen(context, actionBar, statusBar) as RealVideo
        video.mScaleType = mScaleType
        video.isMainStream = isMainStream
        video.isNeedMute = isNeedMute
        video.isChoose = isChoose
        video.resolveStreamUI()
        video.resolveTypeUI()
        video.resolveVoice()
        return video
    }

    override fun cloneParams(from: GSYBaseVideoPlayer?, to: GSYBaseVideoPlayer?) {
        super.cloneParams(from, to)
        val sf = from as RealVideo
        val st = to as RealVideo
        st.streamChangeListener = sf.streamChangeListener
    }

    override fun resolveNormalVideoShow(
        oldF: View?,
        vp: ViewGroup?,
        gsyVideoPlayer: GSYVideoPlayer?
    ) {
        super.resolveNormalVideoShow(oldF, vp, gsyVideoPlayer)
        gsyVideoPlayer?.let {
            val video: RealVideo = it as RealVideo;
            isNeedMute = video.isNeedMute
            isChoose = video.isChoose
            isMainStream = video.isMainStream
            mScaleType = video.mScaleType
            resolveVoice()
            resolveTypeUI()
            resolveStreamUI()
        }

    }

    override fun getGSYVideoManager(): GSYVideoViewBridge {
        RealVideoManager.getCustomManager(getKey()).initContext(context.applicationContext)
        return RealVideoManager.getCustomManager(getKey())
    }

    override fun backFromFull(context: Context): Boolean {
        return RealVideoManager.backFromWindowFull(context, getKey())
    }

    public override fun releaseVideos() {
        RealVideoManager.releaseAllVideos(getKey())
    }


    override fun getFullId(): Int {
        return RealVideoManager.FULLSCREEN_ID
    }

    override fun getSmallId(): Int {
        return RealVideoManager.SMALL_ID
    }

    override fun changeNeedMutes(isNeedMutes: Boolean) {
        if (!mHadPlay) return
        this.isNeedMute = isNeedMutes
        ivSwitchVoice.isSelected = isNeedMutes
        RealVideoManager.getCustomManager(getKey()).isNeedMute = isNeedMutes
    }

    /** 码流变化监听 */
    private var streamChangeListener: OnStreamChangeListener? = null
    fun setOnStreamChangeListener(streamChangeListener: OnStreamChangeListener) {
        this.streamChangeListener = streamChangeListener
    }

    interface OnStreamChangeListener {
        fun onChange(isMainStream: Boolean)
    }

    /**
     * 选中变红
     *
     * @param isChoose
     */
    override fun changeVideo(isChoose: Boolean) {
        this.isChoose = isChoose
        if (isChoose) {
            isThis = true
            rlVideo.setBackgroundResource(R.mipmap.bg_video_red)
            ChooseVideoUtil.instance.setPass(index)
        } else {
            isThis = false
            rlVideo.setBackgroundResource(R.mipmap.bg_video)

        }
    }

    private var index: Int = 0
    fun setIndex(index: Int) {
        this.index = index
        if (index == 0) {
            isThis = true
            isChoose = true
            rlVideo.setBackgroundResource(R.mipmap.bg_video_red)
            ChooseVideoUtil.instance.setPass(index)
        } else {
            isThis = false
            isChoose = false
            rlVideo.setBackgroundResource(R.mipmap.bg_video)
        }
    }

    /** Attach 绑定声音和选中监听 */
    fun attachObserver() {
        NeedMutesUtil.instance.attachObserver(getKey(), this)
        ChooseVideoUtil.instance.attachObserver(getKey(), this)
        RealVideoManager.getCustomManager(getKey()).isNeedMute = isNeedMute
    }

    /** 解除绑定声音和选中监听 */
    fun detachObserver() {
        NeedMutesUtil.instance.detachObserver(getKey())
        ChooseVideoUtil.instance.detachObserver(getKey())
    }

}
